<template>
  <div class="contract-container">
    <el-row :gutter="20">
      <!-- 左侧区域 -->
      <el-col :span="16">
        <!-- 市场行情部分 -->
        <el-card class="contract-card market-card">
          <template #header>
            <div class="card-header">
              <span>市场行情</span>
              <el-tag type="success" size="small">实时更新</el-tag>
            </div>
          </template>
          <div class="market-content">
            <el-table 
              :data="topCryptos" 
              style="width: 100%" 
              :loading="loading"
              stripe
              height="400"
            >
              <el-table-column prop="symbol" label="交易对" width="120">
                <template #default="scope">
                  <span class="symbol">{{ scope.row.symbol }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格(USDT)" width="150" align="right">
                <template #default="scope">
                  <span :class="scope.row.priceChangePercent >= 0 ? 'up' : 'down'">
                    ${{ formatPrice(scope.row.price) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="priceChangePercent" label="24h涨跌" width="120" align="right">
                <template #default="scope">
                  <span :class="scope.row.priceChangePercent >= 0 ? 'up' : 'down'">
                    {{ scope.row.priceChangePercent >= 0 ? '+' : '' }}{{ scope.row.priceChangePercent.toFixed(2) }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="quoteVolume" label="24h交易量" align="right">
                <template #default="scope">
                  ${{ formatVolume(scope.row.quoteVolume) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="update-time" v-if="lastUpdated">
              最后更新: {{ lastUpdated }}
            </div>
          </div>
        </el-card>

        <!-- 交易模型部分 -->
        <el-card class="contract-card model-card">
          <template #header>
            <div class="card-header">
              <span>交易模型</span>
            </div>
          </template>
          <div class="model-content">
            <el-row :gutter="15">
              <el-col :span="8" v-for="model in tradingModels" :key="model.id">
                <el-card class="model-item" shadow="hover">
                  <div class="model-icon">
                    <el-icon size="24" :color="model.color"><component :is="model.icon" /></el-icon>
                  </div>
                  <div class="model-info">
                    <h4>{{ model.name }}</h4>
                    <p>{{ model.description }}</p>
                  </div>
                  <div class="model-status">
                    <el-tag :type="model.status === 'active' ? 'success' : 'info'" size="small">
                      {{ model.status === 'active' ? '已启用' : '未启用' }}
                    </el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧区域（留空） -->
      <el-col :span="8">
        <el-card class="contract-card">
          <template #header>
            <div class="card-header">
              <span>合约交易</span>
            </div>
          </template>
          <div class="contract-content">
            <div class="placeholder">
              <el-icon size="48" color="#C0C4CC"><Document /></el-icon>
              <p>合约交易功能区域</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { 
  TrendCharts, 
  DataAnalysis, 
  MagicStick, 
  Cpu,
  Document,
  SetUp
} from '@element-plus/icons-vue'

// 市场行情数据
const topCryptos = ref([])
const loading = ref(false)
const lastUpdated = ref('')
const updateInterval = ref(null)

// 交易模型数据（大模型）和配置
const tradingModels = ref([
  {
    id: 1,
    name: 'DeepSeek',
    description: '深度求索大模型',
    icon: 'Cpu',
    color: '#409eff',
    status: 'active',
    apiKey: 'deepseek-api-key-placeholder',
    apiUrl: 'https://api.deepseek.com/v1/chat/completions'
  },
  {
    id: 2,
    name: 'Qwen',
    description: '通义千问大模型',
    icon: 'MagicStick',
    color: '#67c23a',
    status: 'active',
    apiKey: 'qwen-api-key-placeholder',
    apiUrl: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'
  },
  {
    id: 3,
    name: 'GLM',
    description: '智谱清言大模型',
    icon: 'SetUp',
    color: '#e6a23c',
    status: 'inactive',
    apiKey: 'glm-api-key-placeholder',
    apiUrl: 'https://open.bigmodel.cn/api/paas/v4/chat/completions'
  },
  {
    id: 4,
    name: 'Moonshot',
    description: '月之暗面大模型',
    icon: 'DataAnalysis',
    color: '#f56c6c',
    status: 'active',
    apiKey: 'moonshot-api-key-placeholder',
    apiUrl: 'https://api.moonshot.cn/v1/chat/completions'
  },
  {
    id: 5,
    name: 'Baichuan',
    description: '百川大模型',
    icon: 'TrendCharts',
    color: '#909399',
    status: 'inactive',
    apiKey: 'baichuan-api-key-placeholder',
    apiUrl: 'https://api.baichuan-ai.com/v1/chat/completions'
  },
  {
    id: 6,
    name: 'ChatGLM',
    description: 'ChatGLM大模型',
    icon: 'Cpu',
    color: '#409eff',
    status: 'active',
    apiKey: 'chatglm-api-key-placeholder',
    apiUrl: 'https://open.bigmodel.cn/api/paas/v4/chat/completions'
  }
])

// 格式化价格显示
const formatPrice = (price) => {
  const num = parseFloat(price)
  if (num < 1) {
    return num.toFixed(6)
  } else if (num < 100) {
    return num.toFixed(4)
  } else {
    return num.toFixed(2)
  }
}

// 格式化交易量显示
const formatVolume = (volume) => {
  const num = parseFloat(volume)
  if (num >= 1000000000) {
    return (num / 1000000000).toFixed(2) + 'B'
  } else if (num >= 1000000) {
    return (num / 1000000).toFixed(2) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(2) + 'K'
  } else {
    return num.toFixed(2)
  }
}

// 获取Binance交易对数据
const fetchTopCryptos = async () => {
  try {
    loading.value = true
    
    // 获取所有交易对的24小时统计信息
    const response = await axios.get('https://api.binance.com/api/v3/ticker/24hr', {
      timeout: 10000
    })
    
    if (response.data && Array.isArray(response.data)) {
      // 筛选出USDT交易对
      const usdtPairs = response.data.filter(item => 
        item.symbol.endsWith('USDT') && 
        !item.symbol.startsWith('USDT') &&
        parseFloat(item.quoteVolume) > 0
      )
      
      // 按交易量排序并取前10
      const top10 = usdtPairs
        .sort((a, b) => parseFloat(b.quoteVolume) - parseFloat(a.quoteVolume))
        .slice(0, 10)
        .map(item => ({
          symbol: item.symbol,
          price: parseFloat(item.lastPrice),
          priceChangePercent: parseFloat(item.priceChangePercent),
          quoteVolume: parseFloat(item.quoteVolume)
        }))
      
      topCryptos.value = top10
      lastUpdated.value = new Date().toLocaleTimeString()
    }
  } catch (error) {
    console.error('获取Binance数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 向大模型发送请求获取交易建议
const getTradingAdvice = async (model, cryptoData) => {
  try {
    const prompt = `基于以下加密货币市场数据，请提供交易建议：
    
    交易对: ${cryptoData.symbol}
    当前价格: $${cryptoData.price}
    24小时涨跌: ${cryptoData.priceChangePercent}%
    24小时交易量: $${formatVolume(cryptoData.quoteVolume)}

    请分析该币种的短期走势并给出明确的交易建议（买入/卖出/持有）以及理由。`

    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${model.apiKey}`
    }

    // 根据不同模型调整请求格式
    let requestData
    if (model.name === 'Qwen') {
      // 阿里云百炼平台的请求格式
      requestData = {
        model: 'qwen-turbo',
        input: {
          prompt: prompt
        },
        parameters: {
          max_tokens: 512,
          temperature: 0.7
        }
      }
      headers['Authorization'] = `Bearer ${model.apiKey}`
      headers['X-DashScope-SSE'] = 'enable'
    } else {
      // OpenAI兼容格式
      requestData = {
        model: model.name.toLowerCase(),
        messages: [
          {
            role: 'system',
            content: '你是一个专业的加密货币交易顾问，根据市场数据提供交易建议。'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        max_tokens: 512,
        temperature: 0.7
      }
    }

    const response = await axios.post(model.apiUrl, requestData, {
      headers: headers,
      timeout: 30000
    })

    // 解析响应数据（根据不同的API格式）
    if (model.name === 'Qwen') {
      return response.data.output.text
    } else {
      return response.data.choices[0].message.content
    }
  } catch (error) {
    console.error(`获取${model.name}模型建议失败:`, error)
    return `获取${model.name}模型建议失败，请检查配置或网络连接。`
  }
}

// 获取所有启用模型的交易建议
const getAllTradingAdvices = async () => {
  const activeModels = tradingModels.value.filter(model => model.status === 'active')
  const cryptoData = topCryptos.value[0] // 使用排名第一的币种作为示例
  
  if (!cryptoData) return
  
  // 并行请求所有启用的模型
  const advicePromises = activeModels.map(model => 
    getTradingAdvice(model, cryptoData).then(advice => ({
      model: model.name,
      advice: advice
    }))
  )
  
  try {
    const advices = await Promise.all(advicePromises)
    console.log('各模型交易建议:', advices)
    // 这里可以将建议展示在界面上
    return advices
  } catch (error) {
    console.error('获取交易建议失败:', error)
  }
}

// 启动定时更新
const startAutoUpdate = () => {
  // 立即获取一次数据
  fetchTopCryptos()
  
  // 每分钟更新一次市场数据
  updateInterval.value = setInterval(() => {
    fetchTopCryptos().then(() => {
      // 获取市场数据后，请求大模型的交易建议
      getAllTradingAdvices()
    })
  }, 60000) // 60秒 = 1分钟
}

// 清理定时器
const stopAutoUpdate = () => {
  if (updateInterval.value) {
    clearInterval(updateInterval.value)
    updateInterval.value = null
  }
}

// 组件挂载时启动自动更新
onMounted(() => {
  startAutoUpdate()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoUpdate()
})
</script>

<style scoped>
.contract-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.contract-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.market-card {
  height: 500px;
}

.model-card {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.symbol {
  font-weight: bold;
  color: #303133;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.update-time {
  margin-top: 15px;
  text-align: right;
  font-size: 12px;
  color: #909399;
}

.model-content {
  height: 200px;
  overflow-y: auto;
}

.model-item {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.model-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}

.model-icon {
  text-align: center;
  margin-bottom: 10px;
}

.model-info h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #303133;
}

.model-info p {
  margin: 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.model-status {
  margin-top: 10px;
  text-align: right;
}

.contract-content {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder {
  text-align: center;
  color: #C0C4CC;
}

.placeholder p {
  margin-top: 10px;
  font-size: 14px;
}
</style>